package com.ibm.workplace.wcm.cqplugin.ui.preference;

import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.cq.CqConnectionProfile;

public class AddCqConnectionProfileDialog extends Dialog {
    
    private CqConnectionProfileComposite ccpc;
    
    private CqConnectionProfile profile;
    private boolean isAdd;
    
    public AddCqConnectionProfileDialog(Shell shell) {
        this(shell, null);
    }
    
    public AddCqConnectionProfileDialog(Shell shell, CqConnectionProfile profile) {
        super(shell);
        
        if (profile == null) {
            isAdd = true;            
            this.profile = new CqConnectionProfile();
        } else {
            isAdd = false;           
            this.profile = profile;
        }
    }

    protected Control createDialogArea(Composite arg0) {
        Composite c = new Composite(arg0, 0);
        GridLayout gridLayout = new GridLayout();
        c.setLayout(gridLayout);
        
        ccpc = new CqConnectionProfileComposite(c, 0);
        ccpc.init(profile);        
        
        return c;
    }

    protected void okPressed() {
        if (!validate()) {
            return;
        }
        
        ccpc.store(profile);        
        
        super.okPressed();
    }

    protected void configureShell(Shell arg0) {
        super.configureShell(arg0);
        
        arg0.setText(isAdd ? "Add Connection Profile" : "Edit Connection Profile");
    }
    
    public CqConnectionProfile getProfile() {
        return profile;
    }
    
    protected boolean validate() {
        CqConnectionProfile tempProfile = new CqConnectionProfile();
        ccpc.store(tempProfile);
        
        if (tempProfile.getName().trim().equals("") || tempProfile.getSchema().trim().equals("") || tempProfile.getHost().trim().equals("") || tempProfile.getPort().trim().equals("") || tempProfile.getUserName().trim().equals("")) {
            MessageDialog.openWarning(getShell(), getShell().getText(), "You must supply a profile name, host, port, schema, and user name.");
            return false;
        } else {
            return true;
        }        
    }

}
